package com.scores.advice;

import com.google.gson.Gson;
import com.scores.utils.Results;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Aspect
@Component
public class LoginAspect {

    @Autowired
    HttpSession session;

    @Autowired
    HttpServletRequest request;

    @Autowired
    HttpServletResponse response;

    @Around("execution(* com.scores.controller.*.*(..))")
    public Object loginAroundMethod(ProceedingJoinPoint point) throws IOException {

        Object result = null;
        try {
//            System.out.println("拦截请求：" + point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName());
            String methodName = point.getSignature().getName();
            if("login".equals(methodName) || "getCode".equals(methodName) || "getUserName".equals(methodName)){
//                System.out.println("登录和验证码放行");
                return point.proceed();
            }else{
                if(session.getAttribute("loginUser") == null) {
//                    System.out.println("用户未登录，拦截请求：" + methodName);
                    Results<String> results = new Results<>("403", "用户未登录，请先登录");
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().write(new Gson().toJson(results));

                }else{
//                    System.out.println("用户已登录，放行请求：" + methodName);
                    return point.proceed();
                }
            }
        } catch (Throwable throwable) {
            Results<String> results = new Results<>("500", "服务器内部错误");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(new Gson().toJson(results));
        } finally {
            String ip = request.getRemoteHost();
            String port = String.valueOf(request.getRemotePort());
            System.out.println("请求来自IP: " + ip + ", 端口: " + port + ", 方法: " + point.getSignature().getName());
        }

        return result;
    }
}
